<template>
  <div>
    <!-- 面包鞋导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 主体区域 -->
    <el-card>
      <el-button type="primary" @click="showAddCateDialog">添加分类</el-button>
      <!-- 数据列表 -->
      <el-table
        :data="cateList"
        row-key="cat_id"
        border
        :tree-props="{ children: 'children' }"
      >
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="分类名称" prop="cat_name"> </el-table-column>
        <el-table-column label="是否有效" width="100">
          <template slot-scope="scope">
            <i
              :class="
                scope.row.cat_deleted ? 'el-icon-error' : 'el-icon-success'
              "
              :style="scope.row.cat_deleted ? 'color:red' : 'color:green'"
            ></i>
          </template>
        </el-table-column>
        <el-table-column label="层级排序" width="100">
          <template v-slot="scope">
            <el-tag v-if="scope.row.cat_level == 0">一级</el-tag>
            <el-tag v-else-if="scope.row.cat_level == 1" type="success"
              >二级</el-tag
            >
            <el-tag v-else-if="scope.row.cat_level == 2" type="warning"
              >三级</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template v-slot="scope">
            <el-button type="primary" size="mini" @click="showEditCateDialog(scope.row.cat_id)"
              ><i class="el-icon-edit"></i>编辑</el-button
            >
            <el-button type="danger" size="mini" @click="deleteCate(scope.row.cat_id)"
              ><i class="el-icon-delete"></i>删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页控件 -->
      <el-pagination
        @size-change="pageSizeChange"
        @current-change="pageNumChange"
        :current-page.sync="queryInfo.pagenum"
        :page-size="queryInfo.pagesize"
        :page-sizes="[5, 10, 15]"
        layout="total,sizes, prev, pager, next,jumper"
        :total="this.total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      :close-on-click-modal="false"
      :show-close="false"
      @closed="addCateDialogClose"
    >
      <el-form
        :model="addCateForm"
        label-width="100px"
        :rules="CateFormRules"
        ref="addCateForm"
        :status-icon="true"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            clearable
            v-model="selectedParentCate"
            :options="parentCateList"
            :props="CascaderProps"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addCate">确定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑分类对话框 -->
    <el-dialog
      title="编辑分类"
      :visible.sync="editCateDialogVisible"
      width="50%"
      :close-on-click-modal="false"
      :show-close="false"
      @closed="editCateDialogClose"
    >
      <el-form
        :model="editCateForm"
        label-width="100px"
        :rules="CateFormRules"
        ref="editCateForm"
        :status-icon="true"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editCate">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      cateList: [],
      total: 0,
      addCateDialogVisible: false,
      addCateForm: {
        cat_pid: 0,
        cat_name: "",
        cat_level: 0,
      },
      CateFormRules: {
        cat_name: [
          { required: true, message: "请输入新分类的名称", trigger: "blur" },
        ],
      },
      parentCateList: [],
      selectedParentCate: [],
      CascaderProps: {
        label: "cat_name",
        value: "cat_id",
        children: "children",
        expandTrigger: "hover",
        checkStrictly: true,
      },
      editCateDialogVisible: false,
      editCateForm: {},
    };
  },
  methods: {
    // 获得分类列表
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.cateList = res.data.result;
      this.total = res.data.total;

      this.$message.success(res.meta.msg);
    },
    // 回到列表第一页
    getAllCateList(){
      this.queryInfo.pagenum=1
      this.getCateList();
    },
    pageSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getCateList();
    },
    pageNumChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getCateList();
    },
    // 展开添加分类对话框并获取1、2级的父级分类
    showAddCateDialog() {
      this.getParentCateList();
      this.addCateDialogVisible = true;
    },
    async getParentCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);

      this.parentCateList = res.data;
      this.$message.success(res.meta.msg);
    },
    // 提交新分类
    addCate() {
      this.$refs.addCateForm.validate(async (valid) => {
        if (!valid) return;
        if (this.selectedParentCate.length > 0) {
          this.addCateForm.cat_pid =
            this.selectedParentCate[this.selectedParentCate.length - 1];
          this.addCateForm.cat_level = this.selectedParentCate.length;
        } else {
          this.addCateForm.cat_pid = 0;
          this.addCateForm.cat_level = 0;
        }
        const { data: res } = await this.$http.post(
          "categories",
          this.addCateForm
        );
        if (res.meta.status !== 201) this.$message.error(res.meta.msg);

        this.getCateList();
        this.addCateDialogVisible = false;
        this.$message.success(res.meta.msg);
      });
    },
    addCateDialogClose() {
      // 重置
      this.$refs.addCateForm.resetFields();
      this.selectedParentCate = [];
      this.addCateForm.cat_level = 0;
      this.addCateForm.cat_pid = 0;
    },
    // 展开编辑分类对话框并获取信息
    async showEditCateDialog(id) {
      const { data: res } = await this.$http.get(`categories/${id}`);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.editCateForm = res.data;
      this.$message.success(res.meta.msg);
      this.editCateDialogVisible = true;
    },
    editCateDialogClose() {
      this.editCateForm = {};
    },
    // 提交编辑的分类
    editCate() {
      this.$refs.editCateForm.validate(async (valid) => {
        const { data: res } = await this.$http.put(
          `categories/${this.editCateForm.cat_id}`,
          {
            cat_name: this.editCateForm.cat_name,
          }
        );
        if (res.meta.status !== 200) this.$message.error(res.meta.msg);
        this.getCateList();
        this.editCateDialogVisible = false;
        this.$message.success(res.meta.msg);
      });
    },
    // 删除指定id的分类
    deleteCate(id){
      this.$confirm("此操作将永久删除该分类, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete("categories/" + id);
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
          
          this.getAllCateList();
          this.$message.success(res.meta.msg);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    }
  },
  created() {
    this.getCateList();
  },
};
</script>
<style lang='less' scoped>
.el-cascader {
  width: 100%;
}
</style>